﻿#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

enum Colour
{
	RED,
	BLACK
};

template<class T>
struct RBTreeNode
{
	RBTreeNode(const T &data)
		:_data(data),
		_left(nullptr),
		_right(nullptr),
		_parent(nullptr),
		_col(RED) 
	{}
	T _data;
	RBTreeNode<T>* _left;
	RBTreeNode<T>* _right;
	RBTreeNode<T>* _parent;
	Colour _col;
};

// 修改迭代器本质是修改迭代器里面指针的指向。
// 封装迭代器一层套一层，RBTreeIterator——>Iterator——>iterator
template<class T, class Ref, class Ptr> // 考虑到普通迭代器和const迭代器，所以加上Ref和Ptr
struct RBTreeIterator
{
	using Node = RBTreeNode<T>;
	using Self = RBTreeIterator<T, Ref, Ptr>;

	RBTreeIterator(Node* node,Node*root)
		:_node(node),
		_root(root)
	{}

	Self& operator++()
	{
		// 右子树不为空（代表当前结点已经访问完了），找右子树最左节点。
		if (_node->_right)
		{
			Node* leftMost = _node->_right;
			while (leftMost->_left)
				leftMost = leftMost->_left;
			_node = leftMost;
		}
		// 右子树为空（代表当前结点已经访问完了且当前结点所在的⼦树也访问完了），找孩子是父亲左的那个祖先
		else
		{
			Node* cur = _node;
			Node* parent = cur->_parent;
			while (parent && parent->_right == cur)
			{
				cur = parent;
				parent = cur->_parent;
			}
			_node = parent;
		}
		return *this;
	}

	Self& operator--()
	{
		if (_node == nullptr) // end()
		{
			// --end()，特殊处理，⾛到中序最后⼀个结点，整棵树的最右结点
			Node* rightMost = _root;
			while (rightMost && rightMost->_right)
				rightMost = rightMost->_right;
			_node = rightMost;
		}
		else
		{
			//左子树不为空（代表当前结点已经访问完了），找左子树最右节点。
			if (_node->_left)
			{
				Node* rightMost = _node->_left;
				while (rightMost->_right)
					rightMost = rightMost->_right;
				_node = rightMost;
			}
			// 左子树为空（代表当前结点已经访问完了且当前结点所在的⼦树也访问完了），找孩子是父亲右的那个祖先
			else
			{
				Node* cur = _node;
				Node* parent = cur->_parent;
				while (parent && parent->_left == cur)
				{
					cur = parent;
					parent = cur->_parent;
				}
				_node = parent;
			}
		}
		return *this;
	}

	Ref operator*()
	{
		return _node->_data;
	}

	Ptr operator->()
	{
		return &_node->_data;
	}

	bool operator==(const Self& s) const
	{
		return _node == s._node;
	}

	bool operator!=(const Self& s) const
	{
		return _node != s._node;
	}

	Node* _node;
	Node* _root;
};

//一份模版，编译器实例化出 key的RBTree 和 pair<K,V>的RBTree
template<class K, class T,class KeyOfT>
class RBTree
{
private:
	using Node = RBTreeNode<T>;

	void RotateL(Node* parent)
	{
		Node* subR = parent->_right;
		Node* subRL = subR->_left;
		parent->_right = subRL;
		if (subRL)
			subRL->_parent = parent;

		Node* pParent = parent->_parent;
		subR->_left = parent;
		parent->_parent = subR;
		if (parent == _root)
		{
			_root = subR;
			subR->_parent = nullptr;
		}
		else
		{
			if (pParent->_left == parent)
				pParent->_left = subR;
			else
				pParent->_right = subR;
			subR->_parent = pParent;
		}
	}

	void RotateR(Node* parent)
	{
		Node* subL = parent->_left;
		Node* subLR = subL->_right;
		parent->_left = subLR;
		if (subLR)
			subLR->_parent = parent;

		Node* pParent = parent->_parent;
		subL->_right = parent;
		parent->_parent = subL;
		if (parent == _root)
		{
			_root = subL;
			subL->_parent = nullptr;
		}
		else
		{
			if (pParent->_left == parent)
				pParent->_left = subL;
			else
				pParent->_right = subL;
			subL->_parent = pParent;
		}
	}

	void Destroy(Node* root)
	{
		if (root == nullptr)
			return;
		Destroy(root->_left);
		Destroy(root->_right);
		delete root;
	}

public:
	using Iterator = RBTreeIterator<T, T&, T*>;
	using ConstIterator = RBTreeIterator<T, const T&, const T*>;
	Iterator Begin()
	{
		Node* leftMost = _root;
		while (leftMost && leftMost->_left)
			leftMost = leftMost->_left;
		return Iterator(leftMost,_root);
	}
	Iterator End()
	{
		return Iterator(nullptr, _root);
	}

	ConstIterator Begin() const
	{
		Node* leftMost = _root;
		while (leftMost && leftMost->_left)
			leftMost = leftMost->_left;
		return Iterator(leftMost, _root);
	}
	ConstIterator End() const
	{
		return Iterator(nullptr, _root);
	}

	RBTree() = default;

	~RBTree()
	{
		Destroy(_root);
		_root = nullptr;
	}

	pair<Iterator,bool> Insert(const T& data)
	{
		if (_root == nullptr)
		{
			_root = new Node(data);
			_root->_col = BLACK;
			return make_pair(Iterator(_root, _root), true);
		}
		KeyOfT kot;
		Node* cur = _root;
		Node* parent = nullptr;
		while (cur)
		{
			if (kot(data) > kot(cur->_data))
			{
				parent = cur;
				cur = cur->_right;
			}
			else if (kot(data) < kot(cur->_data))
			{
				parent = cur;
				cur = cur->_left;
			}
			else
			{
				return make_pair(Iterator(cur, _root), false);
			}
		}
		cur = new Node(data);
		Node* newnode = cur; 

		// 新增结点。颜⾊红⾊给红⾊
		cur->_col = RED;
		if (kot(data) > kot(parent->_data))
			parent->_right = cur;
		else
			parent->_left = cur;
		cur->_parent = parent;
		while (parent && parent->_col == RED)
		{
			Node* grandfather = parent->_parent;
			//	  g
			//	p   u
			if (parent == grandfather->_left)
			{
				Node* uncle = grandfather->_right;
				if (uncle && uncle->_col == RED)
				{
					// u存在且为红 -> 变⾊再继续往上处理
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;
					cur = grandfather;
					parent = cur->_parent;
				}
				else
				{
					// u存在且为⿊或不存在 -> 旋转+变⾊
					if (parent->_left == cur)
					{
						//    g
						//  p   u
						//c
						//单旋
						RotateR(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;

					}
					else
					{
						//   g
						// p   u
						//  c
						//双旋
						RotateL(parent);
						RotateR(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}
			}
			else
			{
				//  g
				//u   p
				Node* uncle = grandfather->_left;
				// 叔叔存在且为红，-> 变⾊即可
				if (uncle && uncle->_col == RED)
				{
					parent->_col = uncle->_col = BLACK;
					grandfather->_col = RED;

					// 继续往上处理
					cur = grandfather;
					parent = cur->_parent;
				}
				// 叔叔不存在，或者存在且为⿊
				else 
				{
					// 旋转+变⾊
					//   g
					// u   p
					//       c
					if (parent->_right == cur)
					{
						RotateL(grandfather);
						parent->_col = BLACK;
						grandfather->_col = RED;

					}
					else
					{
						//   g
						// u   p
						//    c
						RotateR(parent);
						RotateL(grandfather);
						cur->_col = BLACK;
						grandfather->_col = RED;
					}
					break;
				}
			}
		}
		_root->_col = BLACK;

		//新插入的节点不能用cur。如果父亲和叔叔都是红色的，变色后再继续往上处理，此时cur就变了不再是新节点了，所以用newnode提前保存cur。
		return make_pair(Iterator(newnode, _root), true); 
	}

	Iterator Find(const K& key)
	{
		Node* cur = _root;
		KeyOfT kot;
		while (cur)
		{
			if (kot(cur->_data) < key)
			{
				cur = cur->_right;
			}
			else if (kot(cur->_data) > key)
			{
				cur = cur->_left;
			}
			else
			{
				return Iterator(cur, _root);
			}
		}
		return End();
	}
	
private:
	Node* _root = nullptr;
};